<template>
    <div class="header">
        <div class="header-top clearfix">
            <div class="ht-folder float-l posr" v-if="false">
                <span class="ht-folder-btn" :class="fileListVisible ? 'cur': ''" @click.stop="showFileList"><i
                        class="iconfont icon-folder01 mr05"></i>文件</span>
                <ul class="folder-ul" v-show="fileListVisible" @click.stop="showFileList">
                    <li @click="save"><a href="javascript:;"><i class="iconfont icon-save"></i>保存</a></li>
                    <li @click="saveAs" v-show="false"><a href="javascript:;"><i class="iconfont icon-add02"></i>另存为新版本</a>
                    </li>
                    <li class="folde-ul-li posr" @click.self.stop>
                        <a href="javascript:;" @click.self.stop><i class="iconfont icon-download"></i>导出为</a>
                        <i class="iconfont icon-back01 float-r" @click.self.stop></i>
                        <div class="posa folder-ul-item">
                            <span @click="exportWord"><i class="listImg word-type"></i>Word文档</span>
                            <span @click="exportPdf"><i class="listImg pdf-type"></i>Pdf文档</span>
                            <span @click="exportEpub"><i class="listImg epub-type"></i>Epub文档</span>
                        </div>
                    </li>
                </ul>
            </div>
            <div class="ht-tab float-l">
                <span :class="toolbarvisible ? 'cur' : ''" @click="select(1)">开始</span>
                <span :class="!toolbarvisible ? 'cur' : ''" @click="select(0)">插入</span>
             </div>
            <div class="docEditBtn float-l">
                <el-upload class="docImport fl"
                           :action="importUrl"
                           name="FileData"
                           :on-success="fileUploadOk"
                           :on-error="fileUploadFalse"
                           :before-upload="beforeFileUpload"
                           :show-file-list="false">导入文档</el-upload>
                <div class="exportBox">
                    <span class="export">导出为</span>
                    <ins class="exTran"></ins>
                    <ul class="exUL">
                        <!--<li>-->
                            <!--<a :href="exportWorkUrl"><img src="../../assets/images/sj_word.png" />Word文档</a>-->
                        <!--</li>-->
                        <li @click="exportFile('WORD')">
                           <img src="../../assets/images/sj_word.png" />Word文档
                        </li>
                        <li @click="exportFile('PDF')"><img src="../../assets/images/sj_pdf.png" />Pdf文档</li>
                        <li @click="exportFile('EPUB')"><img src="../../assets/images/sj_epub.png" />Epub文档</li>
                    </ul>
                </div>
            </div>
            <div class="docEditBtn float-l" v-if="isDeveloping">
                <div @click="test()">主动插入资源按钮</div>
            </div>
            <div class="docEditBtn float-l" v-if="isDeveloping">
                <div @click="exportFile('PDF')">主动导出pdf按钮</div>
            </div>
        </div>
        <div class="header-content clearfix">
            <div class="edit-header clearfix float-l">
                <toolbar v-show="toolbarvisible"></toolbar>
                <insertbar v-show="!toolbarvisible"></insertbar>
            </div>
            <div class="float-r btn-edu">
                <div><ins class="saving" v-show="isShowSaveIcon"></ins><span class="lastSave">{{saveMsg}}</span></div>
                <div style="text-align: center;">
                    <a @click="save">
                        <span class="saveBtn">保存</span>
                    </a>
                    <a @click="closeEditor">
                        <span class="closeBtn">关闭</span>
                    </a>
                </div>
            </div>
        </div>

    </div>
</template>

<script>
    import Toolbar from './toolbar/Toolbar'
    import Insertbar from './toolbar/Insertbar'
    import {Observer} from '../core/util'
    import {DOC_TYPE, PDF_TYPE, EPUB_TYPE} from '../core/constant'
    import {mapGetters, mapMutations, mapActions, mapState} from 'vuex'
    import api from '../api/'
    import eRes from '../../core/editorRes'

    export default {
        components: {
            Toolbar,
            Insertbar
        },
        mounted() {
            Observer.register('globalClick hidecloth', () => {
                this.fileListVisible = false;
            });
        },
        data() {
            return {
                toolbarvisible: true,
                fileListVisible: false,
                uploadLoading: null,
                importUrl: globalVar.baseURL + '/api/File/Word2HtmlContentV2', // 导入文档的路径
            }
        },
        computed: {
            ...mapState(["saveMsg", "isShowSaveIcon"]),
            isDeveloping(){
                return process.env.NODE_ENV === "development";
            }
        },
        methods: {
            ...mapMutations(['focus']),
            ...mapActions(['export', 'save', 'closeEditor']),
            showMsg({msg, type='error'}){
                this.$message({
                    message: msg,
                    type: type,
                    showClose: true,
                    duration: 2000
                });
            },
            select(toolbarvisible) {
                this.focus();
                return this.toolbarvisible = !!toolbarvisible;
            },
            showFileList() {
                this.fileListVisible = !this.fileListVisible;
                Observer.fire(this.fileListVisible ? 'showcloth' : 'hidecloth');
            },
            saveAs() {
                this.$message({
                    message: '功能暂未实现',
                    type: 'warning'
                });
            },
            exportFile(type){
                api.initEditorContent().then(({content, title}) => {
                    console.log(content);
                    if(content){
                        if(type === "PDF"){
                            let editor = UE.getEditor(window.editorId);
                            this.getPdf({title, content, editor});
                        }else{
                            this.export(type === "WORD" ? DOC_TYPE : type === "EPUB" ? EPUB_TYPE : "");
                        }
                    }else{
                        alert('导出内容不能为空！请输入内容并保存！')
                    }
                }).catch(err => {
                    // 初始化失败
                    this.showMsg({
                        msg: '获取编辑器内容失败!'
                    });
                    console.log(err);
                });
            },
            fileUploadOk(response, file, fileList) {
                if (response.Code == 200) {
                    let content = response.Data || "";
                    content = content.replace(/<img[^>]+/g,function (img) {
                      let changeRole = img.replace(/role="\d+"/g, "role=\"999\"");
                      return changeRole.replace(/style=""/g, "style=\"max-width:100%\"");
                    })
                    let editor = UE.getEditor(window.editorId);
                    editor.setContent(content);
                    //主要是为了保存上传的文档中的图片样式修改
                    Observer.fire("saveContent");
                } else {
                    this.showMsg({
                        msg: "上传接口出错！"
                    });
                }
                this.uploadLoading.close();
            },
            fileUploadFalse(err, file, fileList) {
                this.showMsg({
                    msg: "上传失败！"
                });
                this.uploadLoading.close();
            },
            beforeFileUpload(file) {
                let name = file.name,
                    index = name.lastIndexOf("."),
                    type = name.substring(index + 1, name.length),
                    filename = name.substring(0, index);
                type = type.toLowerCase();
                if (type !== "doc" && type !== "docx") {
                    this.showMsg({
                        msg: '只能上传后缀名为doc、docx的文件!'
                    });
                    return false;
                }
                if (file.size == 0) {
                    this.showMsg({
                        msg: '上传文件需大于0KB!'
                    });
                    return false;
                }
                if ((file.size / 1024 / 1024).toFixed(2) > 500) {
                    this.showMsg({
                        msg: '支持上传小于500MB的文件!'
                    });
                    return false;
                }
                var containSpecial = RegExp(/[\$\*\<\>\`\~\^\|\/\\]/g);
                if(containSpecial.test(filename)){
                    this.showMsg({
                        msg: '文件名称不能包含特殊字符：$*<>`~^|/\\'
                    });
                    return false;
                }
                this.uploadLoading = this.$loading({
                    lock: true,
                    text: '导入中，请稍后...'
                });
            },
            test(){
                eRes.addResource({
                  type: 'video',
                  ifrSrc: "//1256464842.vod2.myqcloud.com/vod-player/1256163091/5285890787178319557/tcplayer/console/vod-player.html?autoplay=false&width=1920&height=1080",
                  name: '测试视频.mp4'
                });
            }
        }
    }
</script>
<style>
    .saveBtn, .closeBtn {
        width: 45px;
        display: inline-block;
        height: 22px;
        line-height: 22px;
        border-radius: 2px;
        border: none;
        background: #42a5f5;
        color: #fff;
        font-size: 12px;
        text-align: center;
        cursor: pointer;
    }
    .closeBtn {
        border: 1px solid #dcdcdc;
        background: #f5f5f5;
        color: #666666;
    }
    .btn-edu {
        position: absolute;
        top: 12px;
        right: 5px;
    }
    .docImport:hover:after {
        display: block;
        width: 300px;
        line-height: 18px;
        color: #fc755a;
        text-align: left;
        position: absolute;
        top: 35px;
        left: 0px;
        font-size:12px;
        border: 1px solid #00a4e6;
        -webkit-box-shadow: 0px 0px 5px rgba(200, 200, 200, .6);
        box-shadow: 0px 0px 5px rgba(200, 200, 200, .6);
        padding:10px;
        box-sizing:border-box;
        background-color:#fff;
        z-index:10;
        content: "支持文档格式doc、docx! 限10000字符以内，文件大小20M以内。";
    }
</style>
